package com.blb.edusearchservice.listener;

import com.alibaba.fastjson.JSON;
import com.blb.common.entity.Course;
import com.blb.common.util.RabbitMQConfig;
import com.blb.edusearchservice.service.CourseIndexService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.blb.common.util.RabbitMQConfig.KEY_COURSE_SAVE;

@Slf4j
@Component
public class CourseMQListener {

    @Autowired
    private CourseIndexService courseIndexService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 处理保存课程消息
     * @param data
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfig.QUEUE_COURSE_SAVE})
    public void handleSaveCourse(String data, Channel channel, Message message){
        System.out.println("收到保存课程：" + data);
        //获得消息的id
        String id = message.getMessageProperties().getHeader("spring_returned_message_correlation");
        //使用setNx名保存键，不存在就消费，存在就不消费
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        try {
            if(ops.setIfAbsent(id,"0",100L, TimeUnit.SECONDS)){
                log.info("id{}不存在，执行业务",id);
                //如果为true，代表键不存在，设置成功
                //将json转换为课程对象
                Course course = JSON.parseObject(data, Course.class);
                courseIndexService.saveCourse(course);
                //处理完后，设置为1代表业务完成
                ops.set(id,"1",100L,TimeUnit.SECONDS);
                //手动确认消息处理完成 参数1 消息的标识 参数2 是否批量确认
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                log.info("课程保存完成：{}",course);

            }else{
                //如果为false，代表键存在，不消费
                log.info("id{}存在，不执行业务",id);
                if("1".equals(ops.get(id))){
                    log.info("业务已经执行完");
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }
            }
        } catch (IOException e) {
            log.error("保存课程出现异常",e);
        }
    }

    /**
     * 处理删除课程消息
     * @param id
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfig.QUEUE_COURSE_REMOVE})
    public void handleRemoveCourse(Long id, Channel channel, Message message){
        System.out.println("收到删除课程的id：" + id);
        try {
            courseIndexService.removeCourse(String.valueOf(id));
            //手动确认消息处理完成 参数1 消息的标识 参数2 是否批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("课程删除完成：{}",id);
        } catch (IOException e) {
            log.error("保存删除出现异常",e);
        }
    }
}
